/**
 * Created by showtan on 2018/12/27.
 * app 首页
 */

import ScrollableTabView from 'react-native-scrollable-tab-view';
import { ScrollView } from 'react-native-mjrefresh';
import TabBarCell from './TabBarCell';
let currentPage = 1;
let showCount = 10;
let isFirstLoad = true; // 第一次加载
let isLoading = true;
let isRefreshing = false;
let isLoadMore = false;
class HomePage extends Component {

  static navigationOptions = ({ navigation }) => ({
    tabBarOnPress: (e) => {
      DeviceEventEmitter.emit('homeUserUpdate', 11111); // 监听变化更新
      navigation.navigate('Home', {}); // 需跳转  否则无法切换
    }
  });

  constructor(props) {
    super(props);
    this.state = {
      data1: [1, 1, 1, 1, 1, 1, 1, 1],
      data2: ['row 1', 'row 2', 'row 3'],
      onclick: false,
      text: ''
    }
  }

  /**
   * 数据加载
   * @param {分页} currentPage 
   * @param {每页条数} showCount 
   * @param {正在加载} isLoading 
   * @param {下拉刷新} isRefreshing 
   * @param {加载更多} isLoadMore 
   */
  _loadData(currentPage, isLoading, isRefreshing, isLoadMore) {
    let params = {
      showCount: showCount,
      currentPage: currentPage,
      isLoading: isLoading,
      isRefreshing: isRefreshing,
      isLoadMore: isLoadMore
    };
    // this.props.dispatch({ type: 'task/taskList', payload: params });
  }

  componentDidMount() {
    currentPage = 1; isFirstLoad = true;
    DeviceEventEmitter.addListener('homeUserUpdate', (val) => { this.setState({ onclick: true }); console.log(33333333333) }); // 监听
    InteractionManager.runAfterInteractions(() => {
      this._loadData(currentPage, isLoading, isRefreshing, isLoadMore);
      this.props.task.isLoading = true;
    });
    Geolocation.getCurrentPosition(location => {
      console.log('location', location);
      YXStorage.save('location', { lat: location.coords.latitude, long: location.coords.longitude });
    }, error => {
      console.log('error', error)
      Toast.fail('获取地理位置信息失败!');
    })
  }

  _onEndReach = () => { // 加载更多 
    global.consoleLog && console.log(isFirstLoad)
    if (!isFirstLoad && (currentPage == this.props.task.currentPage)) {
      currentPage += 1;
      global.consoleLog && console.log(this.props.task, this.props.task.isLoadMore)
      if (this.props.task.isLoadMore) {
        this._loadData(currentPage, !isLoading, isRefreshing, !isLoadMore);
      }
    }
  }

  _onRefresh = () => { // 下拉刷新
    currentPage = 1; //初始化到第一页
    this._loadData(currentPage, !isLoading, !isRefreshing, isLoadMore);
    setTimeout(() => {
      this._hw && this._hw.finishRefresh()
    }, 1500)
  }

  _renderFooter = () => { // 底部
    return (
      (this.props.task.total > showCount * currentPage && this.props.task.isLoadMore) ?
        <StaticContainer>
          <LoadMoreFooter />
        </StaticContainer> : <View style={{ justifyContent: 'center', alignItems: 'center', marginVertical: adapt(6) }}>
          <Text style={{ color: '#626262' }}>没有更多推荐了!</Text>
        </View>
    )
  }

  // shouldComponentUpdate(nextProps, nextState) {
  //   return this.state.index !== nextState.index;
  // }

  componentDidUpdate() {
    const { task } = this.props;
    if (task.list_status == 0) {
      task.list_status = -1; this._hw && this._hw.finishRefresh();
    } else if (task.list_status == 1) {
      task.list_status = -1; Toast.info(task.backMessage);
    }
  }

  render() {
    let data = [
      {
        title: '国家公布“限载令”所有原材料上涨达15%！', from: '新华网', comment: '1评论', time: '刚刚', img: [Images.other.icon_flatlist, Images.other.icon_flatlist]
      }, {
        title: '国家公布“限载令”所有原材料上涨达15%！', from: '新华网', comment: '1评论', time: '10分钟前', img: [Images.other.icon_flatlist, Images.other.icon_flatlist, Images.other.icon_flatlist]
      }, {
        title: '国家公布“限载令”所有原材料上涨达15%！', from: '新华网', comment: '1评论', time: '20分钟前', img: [Images.other.icon_flatlist]
      }, {
        title: '妻子挪用8岁女儿救命钱补贴娘家，丈夫伤心欲绝后跳楼轻生，对此你怎么看？', from: '新华网', comment: '1评论', time: '30分钟前', img: []
      }, {
        title: '国家公布“限载令”所有原材料上涨达15%！', from: '新华网', comment: '1评论', time: '40分钟前', img: [Images.other.icon_flatlist]
      }, {
        title: '妻子挪用8岁女儿救命钱补贴娘家，丈夫伤心欲绝后跳楼轻生，对此你怎么看？', from: '新华网', comment: '1评论', time: '50分钟前', img: [Images.other.icon_flatlist, Images.other.icon_flatlist]
      }, {
        title: '妻子挪用8岁女儿救命钱补贴娘家，丈夫伤心欲绝后跳楼轻生，对此你怎么看？', from: '新华网', comment: '1评论', time: '1小时前', img: [Images.other.icon_flatlist, Images.other.icon_flatlist, Images.other.icon_flatlist]
      }
    ];
    let tabData = [
      { tabLabel: '推荐', data: data },
      { tabLabel: '关注', data: data },
      { tabLabel: '视频', data: data },
      { tabLabel: '热点', data: data },
      { tabLabel: '娱乐', data: data },
      { tabLabel: '财经', data: data },
      { tabLabel: '问答', data: data }
    ];
    // let tabNames = ['推荐', '关注', '视频', '热点', '娱乐', '财经', '问答'];
    return (
      <View style={styles.container}>
        {/* <StatusBar backgroundColor={themeColor} /> */}
        <View style={styles.searchCellStyle}>
          <TextInput placeholder='🔍 有什么新鲜事' selectionColor={themeColor}
            underlineColorAndroid='transparent' maxLength={25}
            style={styles.textInputStyle}
            onChangeText={(text) => this.setState({ text })} value={this.state.text} />
          {this.state.text.length > 0 && <TouchableOpacity activeOpacity={.6} style={styles.clearTextCell} onPress={() => this.setState({ text: '' })}>
            <Image source={Images.other.icon_guanbi} style={{ width: adapt(15), height: adapt(15), tintColor: '#8f8e93' }} />
          </TouchableOpacity>}
          <TouchableOpacity activeOpacity={.6}>
            <Text style={{ fontSize: adapt(16), color: '#fff' }}>搜索</Text>
          </TouchableOpacity>
        </View>
        <View style={{ backgroundColor: '#fff', height: adapt(5) }} />
        <ScrollableTabView
          showsVerticalScrollIndicator={false}
          // renderTabBar={() => <TabBarCell tabNames={tabNames} />}
          locked={isIOS ? false : true}
          tabBarBackgroundColor='#fff'
          tabBarActiveTextColor={themeColor}
          tabBarTextStyle={{ fontSize: adapt(16), marginTop: adapt(8.5) }}
          tabBarUnderlineStyle={{ backgroundColor: themeColor, height: adapt(3), width: adapt(32), marginLeft: adapt(10) }}
          initialPage={0}>
          {
            tabData.map((item, index) => {
              return (
                <FlatList
                  key={index}
                  tabLabel={item.tabLabel}
                  data={item.data}
                  extraData={this.state}
                  renderItem={this._renderItem}
                  ListFooterComponent={this._renderFooter}
                  onEndReachedThreshold={.1}
                  onEndReached={this._onEndReach}
                  onRefresh={this._onRefresh}
                  keyExtractor={(item, index) => index.toString()}
                  renderScrollComponent={props => <ScrollView
                    showsVerticalScrollIndicator={false}
                    style={{ flex: 1 }}
                    refreshControl={
                      <RefreshControlComponent
                        ref={ref => this._hw = ref}
                        onRefresh={this._onRefresh}
                      />
                    }
                  />}
                />
              )
            })
          }
        </ScrollableTabView>
      </View>
    );
  }

  _renderItem = ({ item }) => {
    return (
      <TouchableOpacity onPress={() => { }} activeOpacity={.9} style={[styles.itemCell, item.img.length == 1 && { flexDirection: 'row' }]}>
        <View style={[{ flex: 1 }, item.img.length == 1 && { height: adapt(65), justifyContent: 'space-between' }]}>
          <Text style={{ marginVertical: adapt(8) }}>{item.title}</Text>
          {item.img.length > 1 && <View style={{ flexDirection: 'row' }}>
            {item.img.map((image, index) => <Image key={index} style={[styles.moreImageStyle, index != 2 && { marginRight: adapt(3) }]} source={image} />)}
          </View>}
          <View style={[styles.bottomCellStyle, item.img.length > 1 && { marginTop: adapt(10) }]}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Text style={styles.smallTextStyle}>{item.from}</Text>
              <Text style={styles.smallTextStyle}>{item.comment}</Text>
              <Text style={styles.smallTextStyle}>{item.time}</Text>
            </View>
            <TouchableOpacity style={styles.closeBottonStyle}>
              <Image source={Images.other.icon_guanbi} style={{ width: adapt(15), height: adapt(15), tintColor: '#ccc' }} />
            </TouchableOpacity>
          </View>
        </View>
        {item.img.length == 1 && <Image style={{ width: adapt(100), height: adapt(65), marginLeft: adapt(6) }} source={item.img[0]} />}
      </TouchableOpacity>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: isIphoneX() ? adapt(40) : isIOS ? adapt(20) : 0,
    backgroundColor: '#ededed'
  },
  searchCellStyle: {
    height: adapt(40),
    width: width,
    flexDirection: 'row',
    paddingHorizontal: adapt(15),
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: themeColor
  },
  textInputStyle: {
    height: adapt(28),
    width: width - adapt(70),
    paddingLeft: adapt(8),
    backgroundColor: '#fff',
    borderRadius: adapt(4)
  },
  clearTextCell: {
    position: 'absolute',
    top: adapt(12.5),
    right: adapt(55)
  },
  itemCell: {
    paddingHorizontal: adapt(15),
    paddingVertical: adapt(4),
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: '#ccc',
    backgroundColor: '#fff'
  },
  moreImageStyle: {
    width: (width - adapt(36)) / 3,
    height: adapt(65)
  },
  smallTextStyle: {
    color: '#818181',
    fontSize: adapt(10),
    marginRight: adapt(4)
  },
  closeBottonStyle: {
    width: adapt(14),
    height: adapt(12),
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: '#818181',
    borderWidth: adapt(1),
    borderRadius: adapt(4)
  },
  tastStatus: {
    paddingHorizontal: adapt(4),
    paddingTop: adapt(2),
    paddingBottom: adapt(1.5),
    color: '#fff'
  },
  bottomCellStyle: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start'
  },
});

HomePage.proptypes = {
  task: PropTypes.object,
  dispatch: PropTypes.func
}

function mapStateToProps({ task }) {
  return { task }
}

export default connect(mapStateToProps)(HomePage)